import sublime
import sublime_plugin

class ResponseToJsonCommand(sublime_plugin.TextCommand):
    def run(self, edit):

        # \\\" => '
        region = self.view.find('\\\\\\"', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '\'');
            region = self.view.find('\\\\\\"', 0, sublime.LITERAL)

        # \\ => \
        region = self.view.find('\\\\', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '\\');
            region = self.view.find('\\\\', 0, sublime.LITERAL)

        # "{ => {
        region = self.view.find('"{', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '{');
            region = self.view.find('"{', 0, sublime.LITERAL)

        # }" => }
        region = self.view.find('}"', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '}');
            region = self.view.find('}"', 0, sublime.LITERAL)

        # \" => "
        region = self.view.find('\\"', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '"');
            region = self.view.find('\\"', 0, sublime.LITERAL)

        # "[ => [
        region = self.view.find('"[', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '[');
            region = self.view.find('"[', 0, sublime.LITERAL)

        # ]" => ]
        region = self.view.find(']"', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, ']');
            region = self.view.find(']"', 0, sublime.LITERAL)

        # \r\n => 
        region = self.view.find('\\r\\n', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, '');
            region = self.view.find('\\r\\n', 0, sublime.LITERAL)

        # ,] => ]
        region = self.view.find(',]', 0, sublime.LITERAL)
        while not region.empty():
            self.view.replace(edit, region, ']');
            region = self.view.find(',]', 0, sublime.LITERAL)

        # Set syntax
        self.view.run_command('set_file_type', {"syntax": "Packages/JavaScript/JSON.sublime-syntax"});
        # sublime.run_command('set_file_type', {"syntax": "Packages/JavaScript/JavaScript.sublime-syntax"});

        # Indent
        self.view.run_command('auto_indent')